﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Metro.Kashikoi.ServiceContract.Security;
using Metro.Kashikoi.Service.Common.Entity;
using Metro.Kashikoi.Common.ExceptionHandling;

namespace Metro.Kashikoi.Service.Security.Entity
{
   static class Repository
    {
       public static User GetUser(this Repository<UserBase> repository, int id, string login)
       {
           if (repository.Count<User>(o => o.Id == id) == 1)
           {
               return repository.Single<User>(o => o.Id == id);
           }
           else if (repository.Count<User>(o => o.Login == login) == 1)
           {
               return repository.Single<User>(o => o.Login == login);
           }
           else
           {
               throw new AppException(string.Format("The user with the id{0} does not exist.", id));
           }
       }

       public static User GetLoginUser(this Repository<UserBase> repository, string login, string password)
       {
           if (repository.Count<User>(o => o.Login == login.Trim() && o.Password == password.Trim()) == 1)
           {
               return repository.Single<User>(o => o.Login == login.Trim() && o.Password == password.Trim());
           }
           else
           {
               throw new AppException(string.Format("The login id{0} does not exist or password is not correcct.", login));
           }
       }

       public static UserGroup GetUserGroup(this Repository<UserGroup> repository, int id)
       {
           if (repository.Count<UserGroup>(o => o.Id == id) == 1)
           {
               return repository.Single<UserGroup>(o => o.Id == id);
           }
           else
           {
               throw new AppException(string.Format("The user group with the id{0} does not exist.", id));
           }
       }

       public static IList<User> GetUsers(this Repository<UserBase> repository, int userGroupId)
       {
           return repository.Where<User>(o => o.GroupIdCol.Contains(userGroupId)).ToList();
       }

       public static IEnumerable<UserGroup> GetGroups(this Repository<UserGroup> repository, int userGroupId)
       {
           return repository.Where<UserGroup>(o => o.Id == userGroupId);
       }
        
    }
}
